#include <iostream>

using namespace std;

class Solution
{
public:
    int rangeBitwiseAnd(int left, int right)
    {
        unsigned int res = static_cast<unsigned int>(-1);
        for (int bit = 0; bit < 32; bit++)
        {
            bool notZero = true;
            unsigned int mask = static_cast<unsigned int>(1) << bit;
            if ((left & mask) == 0)
                notZero = false;
            else
            {
                unsigned int checkVal = ((static_cast<long>(left) >> bit) + 1) << bit;
                while (checkVal <= right)
                {
                    if ((checkVal & mask) == 0)
                    {
                        notZero = false;
                        break;
                    }
                    else
                        checkVal += 1 << bit;
                }
            }
            res &= notZero ? static_cast<unsigned int>(-1) : ~mask;
        }
        return res;
    }
};
int main()
{
    cout << "Code201" << endl;
    Solution s;
    cout << s.rangeBitwiseAnd(2147483646, 2147483647) << endl;
    return 0;
}
/*
class Solution
{
public:
    //for bit wise or operation
   int rangeBitwiseAnd(int left, int right)
   {
       int left_bit = 0;
       if (left != 0)
       {
           for (int i = left; i > 0; i >>= 1)
           {
               left_bit++;
           }
           left_bit -= 1;
       }
       int right_bit = 0;
       if (right != 0)
       {
           for (int i = right; i > 0; i >>= 1)
           {
               right_bit++;
           }
           right_bit -= 1;
       }
       int val = 0;
       for (int i = left_bit; i <= right_bit; i++)
       {
           val |= (1 << i);
       }
       return val | left;
   }
};
*/